#!/bin/bash

# ./entrypoint.sh -h 127.0.0.1 -p 3306,2379,6379 -c '/im/bin/file_server -flagfile=./xx.conf'

# 编写一个端口探测函数，端口连接不上则循环等待
function wait_for_port() {
    local host=$1
    local port=$2
    local timeout=$3

    while true; do
        nc -z $host $port
        if [ $? -eq 0 ]; then
            echo "Port $port is open"
            break
        else
            echo "Port $port is not open, waiting..."
            sleep 1
        fi
        timeout=$((timeout-1))
        if [ $timeout -le 0 ]; then
            echo "Timeout waiting for port $port to open"
            exit 1
        fi
    done
}

# 获取命令行参数
# getopts "h:p:c:" arg 表示 h:p:c: 表示 h 后面接一个参数，p 后面接一个参数，c 后面接一个参数赋值给arg
declare host
declare ports
declare command
while getopts "h:p:c:" arg; do
    case $arg in
        h)
            host=$OPTARG
            ;;
        p)
            ports=$OPTARG
            ;;
        c)
            command=$OPTARG
            ;;
        ?)
            echo "Usage:  [-h host] [-p ports] [-c command]"
            exit 1
            ;;
    esac
done

echo "host: $host"
echo "ports: $ports"
echo "command: $command"

# 3.通过执行函数进行端口探测
# ${ports//,/} 是 将字符串中的逗号替换为空字符串，得到一个以空格分隔的数组
for port in ${ports//,/ }; do
    wait_for_port $host $port 60
done

# 4.执行命令
eval $command